#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1
PROG_AIRCAST=/usr/bin/aircast
PROG_AIRUPNP=/usr/bin/airupnp

get_config() {
	config_get enabled $1 enabled "0"
	config_get interface $1 interface "br-lan"
	config_get aircast $1 aircast "1"
	config_get airupnp $1 airupnp "1"
}

start_service() {
	config_load "airconnect"
	config_foreach get_config "airconnect"
	[ $enabled -eq 0 ] && return 0

	# UPnP/Sonos
	if [ "$airupnp" -eq 1 ]; then
		procd_open_instance airupnp
		procd_set_param command $PROG_AIRUPNP
		procd_append_param command -l 1000:2000
		procd_append_param command -Z
		procd_append_param command -b $interface
		procd_set_param stdout 0
		procd_set_param stderr 0
		procd_set_param respawn
		procd_close_instance airupnp
	fi

	# Chromecast
	if [ "$aircast" -eq 1 ]; then
		procd_open_instance aircast
		procd_set_param command $PROG_AIRCAST
		procd_append_param command -l 1000:2000
		procd_append_param command -Z
		procd_append_param command -b $interface
		procd_set_param stdout 0
		procd_set_param stderr 0
		procd_set_param respawn
		procd_close_instance aircast
	fi
}

service_triggers() {
	procd_add_reload_trigger "airconnect"
}

reload_service() {
	stop
	sleep 1
	start
}
